package cn.mesmile.activity.listener1;

import cn.mesmile.activity.util.CustomSpringUtils;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.delegate.event.ActivitiEvent;
import org.activiti.engine.delegate.event.ActivitiEventListener;
import org.activiti.engine.delegate.event.impl.ActivitiEntityEventImpl;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.impl.persistence.entity.TaskEntity;
import org.activiti.engine.task.Task;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zb
 * @date 2021/12/23 15:24
 * @Description 监听任务开始
 */
@Component
@Slf4j
public class TaskCreateListener implements ActivitiEventListener {

    @Override
    public void onEvent(ActivitiEvent event) {
        // 这里的 TaskService 无法自动注入
        TaskService taskService = CustomSpringUtils.getBean(TaskService.class);

        handle(event);
    }

    /**
     * 监听异常处理策略
     * @return
     */
    @Override
    public boolean isFailOnException() {
        return false;
    }

    /**
     * 拦截任务开始
     * @param event
     */
    public void handle(ActivitiEvent event) {
        if (event instanceof ActivitiEntityEventImpl) {
            // 5011
            String processInstanceId = event.getProcessInstanceId();

            ActivitiEntityEventImpl eventImpl = (ActivitiEntityEventImpl) event;

            TaskEntity entity = (TaskEntity)eventImpl.getEntity();

            String assignee = entity.getAssignee();
            String taskDefinitionKey = entity.getTaskDefinitionKey();
            // 5019
            String taskId = entity.getId();

            // >>>>>>>> id:2509, taskDefinitionKey:handleRequest , assignee:null
            log.info(">>>>>>>> taskId:{}, taskDefinitionKey:{} , assignee:{}",taskId, taskDefinitionKey, assignee);
            log.info(">>>>>>>> 任务创建，判断一下，如果是 起草人 节点就自动完成");

            // 这里的 TaskService 不能够自动注入
            TaskService taskService = CustomSpringUtils.getBean(TaskService.class);

            // 动态设置审批人
            taskService.setAssignee(taskId, "userId");
            // 这里查询不到 当前任务，此时数据库里面还没有数据
            Task task2 = taskService.createTaskQuery().taskId(taskId).singleResult();

            // 动态跳过第一个节点  【handleRequest 为流程图第一个节点的id】
            if ("handleRequest".equals(taskDefinitionKey)){
                Map<String, Object> taskVariables = new HashMap<String, Object>();
                taskVariables.put("vacationApproved", "false");
                taskVariables.put("managerMotivation", "We have a tight deadline! 我们的最后期限很紧!");
                // 添加评论
                taskService.addComment(taskId,processInstanceId,"AutoCompleteComment","自动完成任务");
                // 完成任務
                taskService.complete(taskId, taskVariables);
            }

            // 延迟 2 秒钟处理
            new Thread(() -> {
                try {
                    // 等待2秒钟
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                // 查询任务
                Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
                if (task != null){
                    System.out.println("task.getFormKey() = " + task.getFormKey());
                    System.out.println("task.getName() = " + task.getName());
                    System.out.println("task.getAssignee() = " + task.getAssignee());
                }
            }).start();

        }

    }


}
